<?php

namespace service;

use app\api\model\SeparateAccounts;
use app\api\model\SeparateSet;
use app\common\controller\Service;
use app\common\library\job\MysqlJob;
use think\Queue;
use wechat\WechatService;

class OrderService extends Service
{
    private WechatService $wechat;

    function payment($data)
    {
        $set = SeparateSet::get(['secret'=>$data['service_secret']]);
        $service_secret = $data['service_secret'];
        if (empty($set))
            return $this->_jsondate("FAIL","服务商未配置secret");
        $data = [
            'body' => $data['body'],
            'out_trade_no' => $data['out_trade_no'],
            'total_fee' => $data['total_fee'],
            'notify_url' => $data['notify_url'],
            'trade_type' => 'JSAPI',
            'openid' => $data['openid'],
            'sub_mch_id' => $data['sub_mch_id'], //支付子商户号
            'profit_sharing' => 'Y',
        ];
        $this->wechat = new WechatService($data['sub_mch_id'],$set);
        $res = $this->wechat->unifiedorder($data);
        if ($res['result_code'] == 'FAIL')
            return $this->_jsondate($res['result_code'],$res['result_message']);
        $arr = [
            'body' => $data['body'],
            'openid' => $data['openid'],
            'sub_mch_id' => $data['sub_mch_id'],
            'amount' => $data['total_fee'] / 100,
            'notifyurl' => $data['notify_url'],
            'return_data' => json_encode($res),
            'order_id' => $data['out_trade_no'],
            'state' => 2,
            'service_secret' => $service_secret,
            'other_order' => date("YmdHis") . mt_rand(100000, 999999),
        ];
        SeparateAccounts::create($arr);
        // 创建后异步创建码
        Queue::push(MysqlJob::class, ["sub_mch_id"=>$data['sub_mch_id'],'secret'=>$service_secret,
            'openid'=> $data['openid']], 'bind_user');
        return $this->_jsondate("SUCCESS",$res);
    }

    /**
     * 分账
     * @param $data
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\exception\DbException
     */
    function share($data){
        $set = SeparateSet::get(['secret'=>$data['service_secret']]);
        $this->wechat = new WechatService($data['sub_mch_id'],$set);
        $res = $this->wechat->share($data);
        if ($res['result_code'] == 'FAIL')
            return $this->_jsondate($res['result_code'],$res['result_message']);
        else
            return $this->_jsondate("SUCCESS","分账成功");
    }

    /**
     * 领取优惠券
     * @param $data
     * @return array
     */
    function coupon_receive($data,$user_id){
        // 创建后异步创建码
        Queue::push(MysqlJob::class, ["data"=>$data,'user_id'=>$user_id], 'coupon_receive');
    }
}